package com.hp.tiger.chapter6;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author XavierDong
 **/
public class WriteWorker extends Thread {

    private static final Random RANDOM = new Random(System.currentTimeMillis());

    private final SharedData data;

    private final String filler;

    private int index;


    public WriteWorker(SharedData data, String filler) {
        this.data = data;
        this.filler = filler;
    }


    @Override
    public void run() {
        try {
            while (true) {
                char c = nextChar();
                data.write(c);
                TimeUnit.MILLISECONDS.sleep(RANDOM.nextInt(1000));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    private char nextChar() {
        char c = this.filler.charAt(this.index);
        this.index++;
        if (this.index>=this.filler.length())
            this.index = 0;
        return c;
    }
}
